<template>
    <div class="word-recite-view">
      <!-- 半透明毛玻璃背景 -->
      <div class="blur-background"></div>
      <div class="recite-card">
        <!-- 如果尚未开始背诵，就先让用户选择数量 -->
        <div v-if="reciteRecords.length === 0 && !isLoading" class="setup-step">
          <h2 class="mb-4">准备开始背诵</h2>
          <p class="text-muted">
            请选择要背诵的单词数量 (默认 10)：
          </p>
          <input 
            type="number" 
            class="form-control w-auto mx-auto mb-3 text-center" 
            v-model.number="reciteCount"
            min="1"
            style="font-size:1.5rem"
          />
          <button 
            class="btn btn-primary btn-lg px-5"
            @click="startRecite"
          >
            开始
          </button>
        </div>
  
        <!-- 如果正在加载 -->
        <div v-if="isLoading" class="d-flex flex-column align-items-center justify-content-center text-center">
          <div class="spinner-border text-primary mb-3" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <p>正在加载单词，请稍候...</p>
        </div>
  
        <!-- 2. 当前背诵流程展示 -->
        <div v-else-if="reciteRecords.length > 0">
          <div class="progress-step text-center mb-3">
            <small>
              正在背诵: ({{ currentIndex + 1 }}/{{ reciteRecords.length }})
            </small>
          </div>
  
          <!-- 第一步：是否认识 -->
          <div v-if="currentStep === 1">
            <h4 class="mb-3">你认识这个单词吗？</h4>
  
            <div class="word-display">
              <p class="display-4 fw-bold mb-2">
                {{ currentWordDisplay.wordDisplay }}
              </p>
            </div>
  
            <div class="mb-4">
              <button 
                class="btn btn-success me-3"
                @click="handleKnownWord(true)"
              >
                我认识
              </button>
              <button 
                class="btn btn-warning"
                @click="handleKnownWord(false)"
              >
                不认识
              </button>
            </div>
  
            <!-- 不认识时显示的详细信息 -->
            <transition name="fade">
              <div
                v-if="showWordInfo"
                class="info-box mt-3 text-start p-3"
              >
                <h5>详细信息</h5>
                <p class="mb-1">词性: {{ currentWordDisplay.wordTypeLabel }}</p>
                <p class="mb-1">含义: {{ currentWordDisplay.chinese }}</p>
                <p class="mb-1">
                  例句:
                  <span v-for="(sent, idx) in currentWordDisplay.sentences" :key="idx">
                    <br />- {{ sent }}
                  </span>
                </p>
              </div>
            </transition>
          </div>
  
          <!-- 第二步：检测(测试) -->
          <div v-else-if="currentStep === 2">
            <h4 class="mb-3">测试一下，学会了吗？</h4>
            <!-- 单选翻译 -->
            <div class="mb-3 text-start">
              <label class="fw-semibold mb-2">
                请选择单词的正确中文翻译：
              </label>
              <div
                v-for="(option, idx) in currentTestOptions"
                :key="idx"
                class="form-check mb-1"
              >
                <input
                  class="form-check-input"
                  type="radio"
                  :id="'option-' + idx"
                  name="translationOptions"
                  :value="option"
                  v-model="selectedOption"
                />
                <label class="form-check-label" :for="'option-' + idx">
                  {{ option }}
                </label>
              </div>
            </div>
  
            <!-- 句子挖空填空 -->
            <div class="mb-3 text-start">
              <label class="fw-semibold mb-2">
                请将下列句子填入正确的单词：
              </label>
              <p class="alert alert-light">
                {{ fillBlankSentence }}
              </p>
              <div class="d-flex gap-2 align-items-center">
                <input
                  type="text"
                  class="form-control w-auto"
                  v-model="fillBlankInput"
                  placeholder="德语单词"
                />
                <button class="btn btn-info btn-sm" @click="checkFillBlank">
                  检查
                </button>
              </div>
              <div
                v-if="fillBlankFeedback"
                class="mt-2 alert"
                :class="fillBlankFeedbackClass"
              >
                {{ fillBlankFeedback }}
              </div>
            </div>
  
            <button
              class="btn btn-primary"
              :disabled="!canGoNextStep"
              @click="goNextWord"
            >
              下一单词
            </button>
          </div>
  
          <!-- 第三步：结束 -->
          <div v-else>
            <h3 class="mb-3">本次背诵完成！</h3>
            <p>共背诵了 {{ reciteRecords.length }} 个单词，系统将安排后续复习。</p>
            <button
              class="btn btn-success mt-2"
              @click="handleFinish"
            >
              返回
            </button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  /**
   * 背诵单词流程页面 (示例)
   * 可通过 Vue Router 路由进入，也可在一个全屏模态中呈现
   */
  import { computed, ref, onMounted } from "vue";
  import axios from "axios";
  import { useRoute, useRouter } from "vue-router";
  
  export default {
    name: "WordReciteView",
    setup() {
      const route = useRoute();
      const router = useRouter();
  
      const BASE_URL = "http://localhost:8080/recite";
      const isLoading = ref(false);
  
      // 从路由获取 level/stark
      const selectedLevel = ref(route.query.level || null);
      const selectedIsStark = ref(route.query.stark === "true");
  
      const reciteCount = ref(10);
      const reciteRecords = ref([]);
      const currentIndex = ref(0);
      const currentStep = ref(1);
      const showWordInfo = ref(false);
  
      // 选择题相关
      const currentTestOptions = ref([]);
      const selectedOption = ref(null);
  
      // 填空相关
      const fillBlankSentence = ref("");
      const fillBlankInput = ref("");
      const fillBlankFeedback = ref("");
      const fillBlankFeedbackClass = ref("alert-info");
      const canGoNextStep = ref(false);
  
      const getToken = () => {
        return localStorage.getItem("accessToken") || "";
      };
  
      const currentWord = computed(() => {
        if (!reciteRecords.value.length) return null;
        return reciteRecords.value[currentIndex.value];
      });
  
      const currentWordDisplay = computed(() => {
        if (!currentWord.value) {
          return {
            wordDisplay: "",
            chinese: "",
            sentences: [],
            wordTypeLabel: "",
          };
        }
        const w = currentWord.value;
        let wordTypeLabel = "";
        switch (w.word_type) {
          case "N":
            wordTypeLabel = "名词"; break;
          case "V":
            wordTypeLabel = "动词"; break;
          case "A":
            wordTypeLabel = "形容词"; break;
          default:
            wordTypeLabel = "其他";
        }
        return {
          wordDisplay: w.word || "（未获取到单词）",
          chinese: w.chinese || "（未获取到中文翻译）",
          sentences: w.sentences || [],
          wordTypeLabel,
        };
      });
  
      // 重置测试状态
      const resetTestState = () => {
        currentTestOptions.value = [];
        selectedOption.value = null;
        fillBlankInput.value = "";
        fillBlankFeedback.value = "";
        canGoNextStep.value = false;
  
        if (currentWord.value) {
          const realTranslation = currentWord.value.chinese;
          const fakeOptions = [
            "苹果", "桌子", "玩耍", "吃饭", realTranslation,
          ].sort(() => Math.random() - 0.5);
          currentTestOptions.value = fakeOptions;
  
          if (currentWord.value.sentences && currentWord.value.sentences[0]) {
            fillBlankSentence.value = currentWord.value.sentences[0].replace(
              currentWord.value.word,
              "______"
            );
          }
        }
      };
  
      // 开始背诵
      const startRecite = async () => {
        isLoading.value = true;
        try {
          const payload = { count: reciteCount.value, is_stark: selectedIsStark.value };
          if (!selectedIsStark.value) {
            payload.level = selectedLevel.value;
          }
          const resp = await axios.post(`${BASE_URL}/start/`, payload, {
            headers: { Authorization: `Bearer ${getToken()}` },
          });
          if (resp.data.records) {
            reciteRecords.value = resp.data.records;
          } else {
            alert("后端未返回 records，需要额外查询");
          }
          currentIndex.value = 0;
          currentStep.value = 1;
          showWordInfo.value = false;
          resetTestState();
        } catch (err) {
          console.error("开始背诵失败:", err);
          alert("开始背诵失败，请查看控制台");
        } finally {
          isLoading.value = false;
        }
      };
  
      // 是否认识
      const handleKnownWord = async (isKnown) => {
        showWordInfo.value = !isKnown;
        try {
          await axios.post(`${BASE_URL}/update-record/`, {
            record_id: currentWord.value.id,
            is_known: isKnown,
          }, {
            headers: { Authorization: `Bearer ${getToken()}` },
          });
        } catch (err) {
          console.error("更新背诵记录失败:", err);
        }
        // 认识 -> 进入第二步测试
        if (isKnown) {
          currentStep.value = 2;
          resetTestState();
        }
      };
  
      // 检查填空
      const checkFillBlank = () => {
        if (!fillBlankInput.value) {
          fillBlankFeedback.value = "请输入一个单词。";
          fillBlankFeedbackClass.value = "alert-danger";
          return;
        }
        const target = currentWord.value.word;
        if (fillBlankInput.value.trim().toLowerCase() === target.toLowerCase()) {
          fillBlankFeedback.value = "回答正确！";
          fillBlankFeedbackClass.value = "alert-success";
        } else {
          fillBlankFeedback.value = `回答错误，正确答案是：${target}`;
          fillBlankFeedbackClass.value = "alert-danger";
        }
        // 同时检查单选翻译
        if (selectedOption.value === currentWord.value.chinese) {
          canGoNextStep.value = true;
        } else {
          canGoNextStep.value = false;
        }
      };
  
      // 下一单词
      const goNextWord = () => {
        resetTestState();
        currentIndex.value++;
        if (currentIndex.value >= reciteRecords.value.length) {
          currentStep.value = 3; // 结束
        } else {
          currentStep.value = 1;
          showWordInfo.value = false;
        }
      };
  
      // 完成
      const handleFinish = () => {
        // 返回到“背诵中心”页面
        router.push({ name: "ReciteCenter" });
      };
  
      onMounted(() => {
        // 可以在此根据需要，自动弹出数量选择对话框，或自动开始背诵等
        // 本示例里，先等用户点击“开始”按钮再开始
      });
  
      return {
        isLoading,
        reciteCount,
        reciteRecords,
        currentIndex,
        currentStep,
        showWordInfo,
  
        currentWord,
        currentWordDisplay,
        currentTestOptions,
        selectedOption,
        fillBlankSentence,
        fillBlankInput,
        fillBlankFeedback,
        fillBlankFeedbackClass,
        canGoNextStep,
  
        startRecite,
        handleKnownWord,
        checkFillBlank,
        goNextWord,
        handleFinish,
      };
    },
  };
  </script>
  
  <style scoped>
  .word-recite-view {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
  }
  
  /* 毛玻璃背景 */
  .blur-background {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url('https://picsum.photos/1920/1080?grayscale&blur=2') center/cover no-repeat;
    filter: blur(10px);
    transform: scale(1.2);
    z-index: 1;
    opacity: 0.8;
  }
  
  /* 中间容器(卡片/弹窗) */
  .recite-card {
    position: absolute;
    z-index: 2;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    width: 90%;
    max-width: 600px;
    min-height: 400px;
    background: rgba(255,255,255,0.25); 
    backdrop-filter: blur(15px);
    border-radius: 1.5rem;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    padding: 2rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  
  /* “准备开始”部分 */
  .setup-step {
    text-align: center;
  }
  
  /* 步骤的动画过渡 */
  .fade-enter-active, .fade-leave-active {
    transition: opacity .3s;
  }
  .fade-enter, .fade-leave-to {
    opacity: 0;
  }
  
  /* 信息弹出框：淡入淡出 */
  .info-box {
    background-color: rgba(255,255,255,0.35);
    backdrop-filter: blur(12px);
    border-radius: 1rem;
  }
  
  /* 其他小样式 */
  .word-display {
    margin-bottom: 1rem;
  }
  
  .spinner-border {
    width: 3rem; height: 3rem;
  }
  </style>
  